package com.yvon.maple.cloud.web.filter;

import cn.hutool.core.util.URLUtil;
import com.alibaba.fastjson.JSONObject;
import com.yvon.maple.pojo.LoginUser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

import static com.yvon.maple.constants.SystemConstant.Common.STR_LOGIN_USER;


/**
 * @author : Yvon
 * @since : 2021-08-26
 */
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
@RequiredArgsConstructor
public class LoginUserFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String loginUserStr = request.getHeader(STR_LOGIN_USER);
        LoginUser loginUser = setDefaultUser();
        if (Strings.isNotEmpty(loginUserStr)) {
            LoginUser user = JSONObject.parseObject(URLUtil.decode(loginUserStr), LoginUser.class);
            if (Objects.nonNull(user)) {
                loginUser = user;
            }
        }
        LoginUserUtil.setUser(loginUser);
        filterChain.doFilter(request, response);
        LoginUserUtil.remove();
    }


    public LoginUser setDefaultUser() {
        LoginUser loginUser = new LoginUser();
        loginUser.setId(0L);
        loginUser.setUsername("no_user");
        loginUser.setNickname("系统用户");
        loginUser.setIsAdmin(false);
        loginUser.setIsLogin(false);
        return loginUser;
    }

}
